# -*- coding: utf-8 -*-

'''

名称库和ip库复制到mangodb

'''

import pymysql

from pymongo import MongoClient


mango_client_ip = "192.168.0.168";

# 写入文件
def write_to_file(file_name, txt):
    '''''
        讲txt文本存入到file_name文件中
    '''
    print("正在存储文件" + str(file_name));
    # 1 打开文件
    # w 如果没有这个文件将创建这个文件
    '''
    'r'：读

    'w'：写

    'a'：追加

    'r+' == r+w（可读可写，文件若不存在就报错(IOError)）

    'w+' == w+r（可读可写，文件若不存在就创建）

    'a+' ==a+r（可追加可写，文件若不存在就创建）
    '''
    f = open(file_name, 'a+', encoding='utf-8');
    # 2 读写文件
    f.write(str(txt));
    # 3 关闭文件
    f.close();


def name_list_query():
    # 名称库
    conn = pymysql.connect("192.168.0.55", "admin", "123456", "dwc-admin", charset='utf8');
    cur = conn.cursor();

    # 计算总条数
    sql = "SELECT count(*) FROM dwc_name_list  ";
    cur.execute(sql);
    # 获取所有记录列表
    results = cur.fetchall();
    # 总条数
    count = results[0][0];

    sql = "SELECT * FROM dwc_name_list  ";
    cur.execute(sql);
    # 获取所有记录列表
    results = cur.fetchall();

    # 连接mangodb
    mango_conn = MongoClient(mango_client_ip, 27017);
    mango_db = mango_conn.game_server  # 连接mydb数据库，没有则自动创建
    # mango_db.authenticate("root", "987654321");
    my_table = mango_db.game_name_list;

    for row in results:
        id = row[0];
        full_name = row[1];
        status = row[2];
        write_to_file("d:/game_name_list_config.txt", "db.getCollection('game_name_list_config').insert({_id:NumberLong(" + str(id) + "),fullName:'" + str(full_name) + "',status:NumberInt(0),dbConfig:NumberInt(1)});\n");
        #my_table.insert({"_id":id, "fullName":full_name,"status":0});
        print(id, "--", full_name, "---", status);

    cur.close()
    conn.close()


def ip_list_query():
    # 名称库
    conn = pymysql.connect("192.168.0.55", "admin", "123456", "dwc-admin", charset='utf8');
    cur = conn.cursor();

    # 计算总条数
    sql = "SELECT count(*) FROM dwc_ip_list  ";
    cur.execute(sql);
    # 获取所有记录列表
    results = cur.fetchall();
    # 总条数
    count = results[0][0];

    sql = "SELECT * FROM dwc_ip_list  ";
    cur.execute(sql);
    # 获取所有记录列表
    results = cur.fetchall();

    #连接mangodb
    mango_conn = MongoClient(mango_client_ip, 27017);
    mango_db = mango_conn.game_server  # 连接mydb数据库，没有则自动创建
    #mango_db.authenticate("root", "987654321");
    my_table = mango_db.game_ip_list;

    for row in results:
        id = row[0];
        ip_address = row[1];
        write_to_file("d:/game_ip_list_config.txt","db.getCollection('game_ip_list_config').insert({_id:NumberLong("+str(id)+"),ipAddress:'"+str(ip_address)+"',dbConfig:NumberInt(1)});\n");
        #my_table.insert({"_id": id, "ipAddress": ip_address});
        print(id, "--", ip_address);

    cur.close()
    conn.close()

if __name__ == '__main__':
    print("start");
    #ip_list_query();
    name_list_query();
    print("end");